package cn.sq.scaffold.ffmpeg.controller;

import cn.sq.scaffold.ffmpeg.config.ResponseBean;
import cn.sq.scaffold.ffmpeg.config.StatusCode;
import cn.sq.scaffold.ffmpeg.constants.FfmpegConstants;
import cn.sq.scaffold.ffmpeg.exception.BaseExeception;
import cn.sq.scaffold.ffmpeg.exception.FileChangeExeception;
import cn.sq.scaffold.ffmpeg.hander.FfmpegHander;
import cn.sq.scaffold.ffmpeg.utils.CmdUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: SQ
 * Date: 2020/11/17
 * Time: 16:03
 * Description:
 */
@RestController
@RequestMapping("/ffmepge")

public class FfmepgeController {
    @Autowired
    private FfmpegHander ffmpegHander;

    /**
     * 异步转化文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("asyncprocess")
    public ResponseBean asyncprocess(@RequestParam(value = "file") MultipartFile file) throws BaseExeception, FileChangeExeception, IOException {
        String  uuid = UUID.randomUUID().toString();
        String newFilename = uuid+CmdUtils.getFileSuffix(file.getOriginalFilename());
        String newFilepath = FfmpegConstants.UPLOADVIDEO+newFilename;
        boolean asyncprocess = ffmpegHander.asyncprocess(file.getInputStream(),file.getOriginalFilename(),newFilepath);
        return StatusCode.successResponseBean(asyncprocess,newFilename);
    }

    /**
     * 同步转化文件
     *
     * @param file
     * @return file播放地址
     * @throws IOException
     */
    @RequestMapping("syncprocess")
    public ResponseBean syncprocess(@RequestParam(value = "file") MultipartFile file) throws BaseExeception, FileChangeExeception, IOException {
        String syncprocess = ffmpegHander.syncprocess(file.getInputStream(),file.getOriginalFilename());
        return StatusCode.successResponseBean(syncprocess);
    }

    @RequestMapping("uploadimage")
    public ResponseBean uploadimage(@RequestParam(value = "file") MultipartFile file) throws BaseExeception, FileChangeExeception, IOException {
        String fileSuffix = CmdUtils.getFileSuffix(file.getOriginalFilename());
        //新的文件名称
        String output_file_name = FfmpegConstants.UPLOADIMAGE+ UUID.randomUUID() + fileSuffix;
        FileOutputStream fileOutputStream = new FileOutputStream(output_file_name);
        int copy = IOUtils.copy(file.getInputStream(), fileOutputStream);
        return StatusCode.successResponseBean(output_file_name);

    }

}
